var express = require("express");
var uunewid = require("uuid");
var router = express.Router();
const { ohana } = require("ohana-node-orm");
var moment = require("moment");
const tableName = "SAP_JIANGDU_TAGS";
let log = require("cf-nodejs-logging-support");
log.setLoggingLevel("info");
var fs = require("fs");
var Papa = require("papaparse");

function checkData(res, data) {
  if (data == null) {
    res.send(500);
  }
}

router.get("/getMaxIndex", function (req, res, next) {
  // #swagger.tags = ['标签']
  // #swagger.summary = '获取Tag INDEX 最大值'
  /* #swagger.security = [{
               "JiangduJWT": []
  }] */
  /*  #swagger.parameters['TAG_NAME'] = {
                in: 'query',
                description: '标签类别(required) industy/cap/'
  }*/

  const queryData = req.query;
  if (queryData.TAG_NAME) {
    getMaxIndex(queryData).then(result => {
      console.log(
        Object.entries(result[0]));
      res.send(result[0])
    })
  }
  else {
    res.send({ code: -1, message: "please add parameter" })
  }

})

async function getMaxIndex(data) {
  const tagConn = new ohana(tableName); // new ohana('table_name');
  var result = await tagConn.max("INDEX", {
    "TAG_NAME": data.TAG_NAME
  })
  return result;

}

router.get("/", function (req, res, next) {
  // #swagger.tags = ['标签']
  // #swagger.summary = '获取Tag列表'
  /* #swagger.security = [{
               "JiangduJWT": []
  }] */
  /*  #swagger.parameters['TYPE'] = {
                in: 'query',
                description: '标签类别(optional) PO/FI/TA...'
  }*/
  /*  #swagger.parameters['TAG_CATEGORY'] = {
                in: 'query',
                description: '标签类别(optional) industy/cap/'
  }*/
  const queryData = req.query;
  const policy = new ohana(tableName); // new ohana('table_name');
  if (queryData == null) {
    policy
      .find()
      .then((result) => {
        res.send(result);
      })
      .catch((err) => {
        log.error(err);
        res.status(500).send(err);
      });
  } else {
    policy
      .find(queryData)
      .then((result) => {
        res.send(result);
      })
      .catch((err) => {
        log.error(err);
        res.status(500).send(err);
      });
  }
});

router.get("/categoryAndSubCategory", function (req, res, next) {
  getCategory()
    .then((result) => {
      res.send(result);
    })
    .catch((err) => {
      log.error(err);
      res.status(500).send(err);
    });
});

router.post("/search", function (req, res, next) {
  // #swagger.tags = ['标签']
  // #swagger.summary = '搜索tag'
  /* #swagger.security = [{
               "JiangduJWT": []
  }] */
  /*	#swagger.requestBody = {
            required: true,
            content: {
                "application/json": {
                    schema: {
                        $ref: "#/definitions/tag_search"
                    }  
                },
            }
    } */
  const { data } = req.body;
  const user = new ohana(tableName);
  if (!data) {
    user
      .find()
      .then((result) => {
        res.send(result);
      })
      .catch((err) => {
        log.error(err);
        res.status(500).send(err);
      });
  } else {
    user
      .raw(
        "select * from " +
        tableName +
        " where TAG_NAME like '%" +
        data.name +
        "%'"
      )
      .then((result) => {
        res.send(result);
      })
      .catch((err) => {
        log.error(err);
        res.status(500).send(err);
      });
  }
});

router.put("/", function (req, res, next) {
  // #swagger.tags = ['标签']
  // #swagger.summary = '修改Tag'
  /* #swagger.security = [{
               "JiangduJWT": []
  }] */
  /*	#swagger.requestBody = {
            required: true,
            content: {
                "application/json": {
                    schema: {
                        $ref: "#/definitions/tag_update"
                    }  
                },
            }
    } */
  checkData(res, req.body.data);
  const { data } = req.body;
  log.info(data);
  updatePolicy(data)
    .then((result) => {
      log.info(result);
      if (result == 1) {
        res.sendStatus(200);
      } else {
        res.send(500);
      }
    })
    .catch((err) => {
      log.error(err);
      res.status(500).send(err);
    });
});

router.get("/insertTagFromExcel", async (req, res, next) => {
  // #swagger.tags = ['标签']
  // #swagger.summary = '录入标签'
  /* #swagger.security = [{
               "JiangduJWT": []
  }] */
  let { file } = req.query;
  // 读取文件
  let content = fs.readFileSync(file, "utf8");
  let parsedData = [];
  Papa.parse(content, {
    header: true,
    complete: function (results) {
      parsedData = results.data;
    },
  });

  insertTagFromExcel(parsedData)
    .then(() => {
      res.sendStatus(200);
    })
    .catch((err) => {
      log.error(err);
      res.status(500).send(err);
    });
});

async function insertTagFromExcel(parsedData) {
  for (let index = 0; index < parsedData.length; index++) {
    const element = parsedData[index];
    if (element.政策关键词) {
      let data = {};
      data.TAG_ID = uunewid.v4();
      data.TAG_NAME = element.政策关键词;
      data.TYPE = "PO";
      data.TAG_CATEGORY = "政策关键词";
      data.CREATED_AT = moment(new Date()).format("YYYY-MM-DD HH:mm:ss");
      data.UPDATED_AT = moment(new Date()).format("YYYY-MM-DD HH:mm:ss");
      console.log(data);
      insertData(data);
    }
  }
}

/** insert tags */
router.post("/", function (req, res, next) {
  // #swagger.tags = ['标签']
  // #swagger.summary = '新建Tag'
  /* #swagger.security = [{
               "JiangduJWT": []
  }] */
  /*	#swagger.requestBody = {
            required: true,
            content: {
                "application/json": {
                    schema: {
                        $ref: "#/definitions/tag_add"
                    }  
                },
            }
    } */
  const { data } = req.body;
  data.TAG_ID = uunewid.v4();
  data.USER_NAME = "admin";
  insertData(data)
    .then((result) => {
      if (result == 1) {
        res.sendStatus(200);
      } else {
        res.send(500);
      }
    })
    .catch((err) => {
      log.error(err);
      res.status(500).send(err);
    });
});

async function insertData(body) {
  const policy = new ohana(tableName);
  // const result = await policy.updateOrCreate(
  //   { TAG_NAME: body.TAG_NAME, TAG_CATEGORY: body.TAG_CATEGORY,TAG_VALUE:body.TAG_VALUE },
  //   body
  // );
  Object.keys(body).forEach(item => {
    if (!body[item] || body[item] == '') delete body[item]
  })
  let result = await policy.insert(body);
  return result;
}

/**delete policy  */
router.delete("/", function (req, res, next) {
  // #swagger.tags = ['标签']
  // #swagger.summary = '删除Tag'
  /* #swagger.security = [{
               "JiangduJWT": []
  }] */
  /*	#swagger.requestBody = {
            required: true,
            content: {
                "application/json": {
                    schema: {
                        $ref: "#/definitions/tag_delete"
                    }  
                },
            }
    } */
  checkData(res, req.body.data);
  const { data } = req.body;
  deletePolicy(data)
    .then((result) => {
      log.info(result);
      if (result == 1) {
        res.sendStatus(200);
      } else {
        res.send(400);
      }
    })
    .catch((err) => {
      log.error(err);
      res.status(500).send(err);
    });
});

async function updatePolicy(body) {
  const policy = new ohana(tableName); // new ohana('table_name');
  const result = await policy.update(
    {
      TAG_ID: body.TAG_ID,
    },
    body
  );
  return result;
}
async function deletePolicy(body) {
  const policy = new ohana(tableName); // new ohana('table_name');
  const result = await policy.raw(
    'delete from "SAP_JIANGDU_TAGS" where TAG_ID = \'' + body.TAG_ID + "'"
  );
  return result;
}
async function getCategory() {
  const tag = new ohana(tableName);
  let category = await tag.find(["TAG_NAME", "TAG_VALUE"], {
    TAG_CATEGORY: "category",
  });
  let subcategory = await tag.find(["TAG_NAME", "TAG_VALUE"], {
    TAG_CATEGORY: "sub_category",
  });
  category.map((one) => {
    one.subcategory = [];
    subcategory.map((sub) => {
      if (one.TAG_VALUE == sub.TAG_VALUE.substring(0, 2)) {
        one.subcategory.push(sub);
      }
    });
  });
  return category;
}
module.exports = router;
